package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.paramPojo.Movements;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/1 21:19
 */


@Service
public class QuanZiService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PicUploadService picUploadService;


    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RecommendUserService recommendUserService;

    /**
     * 查询好友动态
     *
     * @param page
     * @param pageSize
     * @return
     */

    public PageResult queryPublishList(Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //全局的校验token:
        User user = UserThreadLocal.get();
        if (user == null) {
            //无效token
            return pageResult;
        }

        //token有效：
        PageInfo<Publish> publishPageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = publishPageInfo.getRecords();
        if (records.isEmpty()) {
            return pageResult;
        }

        //查询好友的info信息：
        List<Object> ids = new ArrayList<>();
        for (Publish record : records) {
            Long userId = record.getUserId();
            ids.add(userId);
        }

        //调用封装QuanziLiVoList的方法：
        List<QuanZiVo> quanZiVoList = getQuanZiVoList(records, ids);


        pageResult.setItems(quanZiVoList);
        //对各个信息进行封装：
        return pageResult;
    }


    /**
     * 发布动态
     *
     * @param movements 封装的要发布的参数
     * @return
     */
    public String savePublish(Movements movements) {

        //校验登录信息获取user:
        User user = UserThreadLocal.get();
        if (user == null) {
            return null;
        }

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(movements.getTextContent());
        publish.setLongitude(movements.getLongitude());
        publish.setLatitude(movements.getLatitude());
        publish.setSeeType(1);
        publish.setLocationName(movements.getLocation());

        List<String> results = new ArrayList<>();
        for (MultipartFile file : movements.getImageContent()) {
            PicUploadResult result = picUploadService.upload(file);
            results.add(result.getName());
        }
        publish.setMedias(results);

        return quanZiApi.savePublish(publish);
    }


    /**
     * 查询推荐动态：
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //全局的校验token:
        User user = UserThreadLocal.get();
        if (user == null) {
            //无效token
            return pageResult;
        }

        PageInfo<Publish> publishPageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);

        List<Publish> records = publishPageInfo.getRecords();
        if (records.isEmpty()) {
            return pageResult;
        }

        //查询好友的info信息：
        List<Object> ids = new ArrayList<>();
        for (Publish record : records) {
            Long userId = record.getUserId();
            ids.add(userId);
        }

        List<QuanZiVo> quanZiVoList = getQuanZiVoList(records, ids);

        pageResult.setItems(quanZiVoList);
        return pageResult;
    }


    /**
     * 封装QuanziVo详细信息：
     *
     * @param records
     * @param ids
     * @return
     */
    private List<QuanZiVo> getQuanZiVoList(List<Publish> records, List<Object> ids) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });

        //调用userInfoMapper查询各个发布用户的详细信息：
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(ids);
        Map<Long, UserInfo> map = new HashMap<>();

        //构建userId 与 UserInfo对象的映射关系
        for (UserInfo userInfo : userInfos) {
            map.put(userInfo.getUserId(), userInfo);
        }

        //遍历quanziVO集合，quanziVo的userId 与 UserInfo的userId一致，所以可以用quanziVo的userId当作key
        for (QuanZiVo quanZiVo : quanZiVoList) {
            fillUserInfoToQuanZiVo(map.get(quanZiVo.getUserId()), quanZiVo);
        }
        return quanZiVoList;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        User user = UserThreadLocal.get();

        quanZiVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(quanZiVo.getId()))); // 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        //（1是，0否）
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0);
        quanZiVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(quanZiVo.getId())));
        quanZiVo.setHasLoved(quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0);
        quanZiVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(quanZiVo.getId())));
    }


    /**
     * 动态点赞：
     *
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean aBoolean = quanZiApi.likeComment(user.getId(), publishId);
        if (aBoolean) {
            //查询点赞数量返回：
            return quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    /**
     * 取消点赞
     *
     * @param publishId
     * @return
     */
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean aBoolean = quanZiApi.disLikeComment(user.getId(), publishId);
        if (aBoolean) {
            //查询点赞数量返回：
            return quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    /**
     * 动态喜欢：
     *
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();

        Boolean aBoolean = quanZiApi.loveComment(user.getId(), publishId);
        if (aBoolean) {

            //查询喜欢数返回
            return quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    /**
     * 取消喜欢
     *
     * @param publishId
     * @return
     */
    public Long disLoveComment(String publishId) {

        User user = UserThreadLocal.get();

        Boolean aBoolean = quanZiApi.disLoveComment(user.getId(), publishId);
        if (aBoolean) {
            //查询喜欢数返回
            return quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }


    /**
     * 查询单条动态：
     *
     * @param publishId
     * @return
     */
    public QuanZiVo queryPublishById(String publishId) {

        Publish publish = quanZiApi.queryPublishById(publishId);

        Long userId = publish.getUserId();
        List<Object> userIds = Arrays.asList(userId);
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIds);
        UserInfo userInfo = userInfos.get(0);

        //封装quanziVo信息：
        QuanZiVo quanZiVo = new QuanZiVo();
        quanZiVo.setId(publishId);
        quanZiVo.setTextContent(publish.getText());
        quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
        quanZiVo.setUserId(userId);
        quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

        //执行信息填充
        fillUserInfoToQuanZiVo(userInfo, quanZiVo);
        return quanZiVo;
    }


    /**
     * 查询评论列表：
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (records.size() == 0) {
            return pageResult;
        }

        //查询用户的信息：
        List<Object> userIds = new ArrayList<>();
        for (Comment record : records) {
            userIds.add(record.getUserId());
        }

        //根据Ids查询userInfos:
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIds);

        Map<Long, UserInfo> map = new HashMap<>();
        for (UserInfo userInfo : userInfos) {
            map.put(userInfo.getUserId(), userInfo);
        }
        //获取当前user:
        User user = UserThreadLocal.get();

        List<CommentVo> result = new ArrayList<>();

        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));
            commentVo.setAvatar(map.get(record.getUserId()).getLogo());
            commentVo.setNickname(map.get(record.getUserId()).getNickName());
            result.add(commentVo);
        }

        pageResult.setItems(result);

        return pageResult;
    }


    /**
     * 发表评论：
     *
     * @param publishId
     * @param content
     * @return
     */
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        return quanZiApi.saveComment(user.getId(), publishId, content);
    }


    /**
     * 查询个人的所有动态：publish:
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    public PageResult queryUserPublish(Integer page, Integer pageSize, Long userId) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> publishPageInfo = quanZiApi.queryUserPublish(userId, page, pageSize);

        List<Publish> publishList = publishPageInfo.getRecords();
        if (publishList.size() == 0) {
            //没有发布记录
            return pageResult;
        }

        //封装quanZiVo:
        List<Object> ids = new ArrayList<>();
        for (Publish publish : publishList) {
            Long userId1 = publish.getUserId();
            ids.add(userId1);
        }

        List<QuanZiVo> quanZiVoList = getQuanZiVoList(publishList, ids);

        //调用userInfoMapper查询各个发布用户的详细信息：
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(ids);
        Map<Long, UserInfo> map = new HashMap<>();

        //构建userId 与 UserInfo对象的映射关系
        for (UserInfo userInfo : userInfos) {
            map.put(userInfo.getUserId(), userInfo);
        }

        //遍历quanziVO集合，quanziVo的userId 与 UserInfo的userId一致，所以可以用quanziVo的userId当作key
        for (QuanZiVo quanZiVo : quanZiVoList) {
            fillUserInfoToQuanZiVo(map.get(quanZiVo.getUserId()), quanZiVo);
        }

        pageResult.setItems(quanZiVoList);


        return pageResult;
    }


    /**
     * 查询访客：
     *
     * @return
     */
    public List<VisitorsVo> queryVisitors() {
        User user = UserThreadLocal.get();

        List<Visitors> visitors = visitorsApi.queryMyVisitor(user.getId());
        //构建userId 与visitors的对应关系：
        Map<Long, Visitors> map = new HashMap<>();
        for (Visitors visitor : visitors) {
            map.put(visitor.getVisitorUserId(), visitor);
        }

        //如果没得， 就返回空集合
        if (visitors.size() == 0) {
            return Collections.emptyList();
        }


        //根据id查询访客的详细信息：
        List<Object> visitorUserId = CollUtil.getFieldValues(visitors, "visitorUserId");
        //查询i详细信息：返回所有访客的详细信息list
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(visitorUserId);

        //封装VisitorsVo对象：
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        VisitorsVo visitorsVo = null;
        for (UserInfo userInfo : userInfos) {
            visitorsVo = new VisitorsVo();
            visitorsVo.setId(userInfo.getUserId());
            visitorsVo.setAge(userInfo.getAge());
            visitorsVo.setAvatar(userInfo.getLogo());
            visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
            visitorsVo.setTags(userInfo.getTags().split(","));
            visitorsVo.setNickname(userInfo.getNickName());
            visitorsVo.setFateValue(map.get(visitorsVo.getId()).getScore().intValue());
            visitorsVoList.add(visitorsVo);
        }
        return visitorsVoList;
    }
}
